﻿#include "usermgmt.h"
#include "ui_usermgmt.h"
#include "mainwindow.h"
#include <QDebug>
//#include "mytoolbox2.h"
//#include "adduserdialog.h"
#include <QDateTime>
#include "usertoolbox.h"
#include "userconfigdialog.h"

#include <QCryptographicHash>

UserMgmt::UserMgmt(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UserMgmt)
{
    ui->setupUi(this);

    ui->tableWidget->setColumnHidden(0, true);

    ui->tableWidget->setColumnWidth(1, 100);
    ui->tableWidget->setColumnWidth(2, 400);
    ui->tableWidget->setColumnWidth(3, 200);
    ui->tableWidget->setColumnWidth(4, 200);
    ui->tableWidget->setColumnWidth(5, 200);
    ui->tableWidget->setColumnWidth(6, 150);
    ui->tableWidget->setColumnWidth(7, 200);
    ui->tableWidget->setColumnWidth(8, 200);
    ui->tableWidget->setColumnWidth(9, 100);
    ui->tableWidget->setColumnWidth(10, 260);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

    switchToPage(1);
}

UserMgmt::~UserMgmt()
{
    delete ui;
}

bool UserMgmt::refresh(QSqlQuery query)
{
    if(query.size() <= 0){
        ui->tableWidget->setRowCount(0);
        return false;
    }

    ui->tableWidget->setRowCount(query.size());
    for(int i=0; i<query.size(); i++){
        if(query.next()){
            for(int j=3; j<=8; j++){
                ui->tableWidget->setItem(i,j,new QTableWidgetItem(query.value(j-2).toString()));
                ui->tableWidget->item(i,j)->setTextAlignment(Qt::AlignCenter);
            }

            ui->tableWidget->setItem(i,0,new QTableWidgetItem(query.value(0).toString()));
            ui->tableWidget->setItem(i,1,new QTableWidgetItem(QString("%1").arg((nowPage-1)*pageLineNum+i+1)));
            ui->tableWidget->item(i,1)->setCheckState(Qt::Unchecked);
            ui->tableWidget->setCellWidget(i,2, new UserToolBox(this));//操作栏

            ui->tableWidget->setItem(i,9,new QTableWidgetItem(query.value(7).toInt() == 1 ? "启用" : "禁用"));
            ui->tableWidget->setItem(i,10,new QTableWidgetItem(query.value(8).toDateTime().toString("yyyy-MM-dd hh:mm:ss")));
            //全部居中
            for(int j=1; j<=10; j++){
                if(ui->tableWidget->item(i,j) == nullptr) continue;
                ui->tableWidget->item(i,j)->setTextAlignment(Qt::AlignCenter);
            }
        }else{
            break;
        }
    }
    return true;
}


int UserMgmt::getBtnRow(QPushButton* btn)
{
    //    QPushButton *btn = (QPushButton*) sender();
    int x = btn->parentWidget()->frameGeometry().x();
    int y = btn->parentWidget()->frameGeometry().y();
    QModelIndex index = ui->tableWidget->indexAt(QPoint(x, y));
    //    return ui->tableWidget->item(index.row(), 0)->text();
    return index.row();
}
//功能按钮
void UserMgmt::btn_func_clicked()
{
    int row = getBtnRow((QPushButton*) sender());
    QString tip = QString("确实要重置用户\"%1\"的密码吗?").arg(ui->tableWidget->item(row, 3)->text());
    if(QMessageBox::No == QMessageBox::question(this, "提示", tip, QMessageBox::Yes|QMessageBox::No)) return;

    int id = ui->tableWidget->item(row, 0)->text().toInt();
    //MD5加密
//    QString MD5 = QCryptographicHash::hash(QString("123456").toLatin1(),QCryptographicHash::Md5).toHex();
    QString MD5 = "123456";
    QString sql = QString("UPDATE dm_user SET password='%2' WHERE id='%1'").arg(id).arg(MD5);
    QSqlQuery query(sql);
    Q_UNUSED(query);
}
void UserMgmt::btn_edit_clicked()
{
    int id = ui->tableWidget->item(getBtnRow((QPushButton*) sender()), 0)->text().toInt();
    UserConfigDialog *conf = new UserConfigDialog(this, id);
    conf->show();
}
void UserMgmt::btn_del_clicked()
{
    int row = getBtnRow((QPushButton*) sender());
    QString tip = QString("确实要删除用户\"%1\"吗?").arg(ui->tableWidget->item(row, 3)->text());
    if(QMessageBox::No == QMessageBox::question(this, "提示", tip, QMessageBox::Yes|QMessageBox::No)) return;

    int id = ui->tableWidget->item(row, 0)->text().toInt();
    QString sql = QString("UPDATE dm_user SET delete_flag='1' WHERE id='%1'").arg(id);
    QSqlQuery query(sql);
    Q_UNUSED(query);

    updatePage();
}
//添加
void UserMgmt::on_btn_add_clicked()
{
    UserConfigDialog *conf = new UserConfigDialog(this, -1);
    conf->show();
}
void UserMgmt::on_btn_batch_del_clicked()
{
    QList<int> list;
    for(int i=0; i<ui->tableWidget->rowCount(); i++){
        if(ui->tableWidget->item(i,1)->checkState()){
            list.append(i);
        }
    }
    if(list.size() <= 0){
        QMessageBox::information(this, "提示", "没有选择用户");
        return;
    }
    if(QMessageBox::No == QMessageBox::question(this, "提示",
        QString("确定要删除%1个用户吗？").arg(list.size()), QMessageBox::Yes|QMessageBox::No)) return;

    QSqlQuery query;
    QString log = QString("删除%1个用户:").arg(list.size());
    QString where = " WHERE";
    for(int i=0; i<list.size(); i++){   //list[i]
        log += QString("<%1>").arg(ui->tableWidget->item(list[i],3)->text());
        where += QString(" OR id='%1'").arg(ui->tableWidget->item(list[i],0)->text().toInt());
    }
    where.replace(" WHERE OR", " WHERE");
    qDebug() << "UPDATE dm_user SET delete_flag=1" + where;
    if(query.exec("UPDATE dm_user SET delete_flag=1" + where))
        mydb->addLog(DM_Window->current_user_id, "用户管理", log, "1");

    updatePage();
}

//刷新当前页
void UserMgmt::updatePage()
{
    int page = ui->lineEdit_nowPage->text().toInt();
    switchToPage(page);
}

//翻页部分
void UserMgmt::on_btn_page_minus_clicked(){switchToPage(nowPage-1);}
void UserMgmt::on_btn_page_plus_clicked(){switchToPage(nowPage+1);}
void UserMgmt::on_btn_page_head_clicked(){switchToPage(1);}
void UserMgmt::on_btn_page_end_clicked(){switchToPage(999999999);}
void UserMgmt::switchToPage(int page)
{
    QString table="dm_user u LEFT JOIN dm_organization o ON COALESCE(u.org_no,'')=COALESCE(o.org_no,'')";
    QSqlQuery query = mydb->query(table, "COUNT(*)", keyword);
    if(!query.next()) return;

    totalLineNum = query.value(0).toInt();
    totalPage = (int)ceil((float) totalLineNum/pageLineNum);
    ui->label_pages->setText(QString("/%1").arg(totalPage));

    if(page > totalPage) page = totalPage;
    if(page < 1) page = 1;
    ui->lineEdit_nowPage->setText(QString("%1").arg(page));
    nowPage = page;

    QString limit = QString(" LIMIT %1,%2").arg((page-1)*pageLineNum).arg(pageLineNum);
    QString cols = "u.id,u.login_name,u.username,o.org_full_name,u.position,u.phone,u.email,u.status,u.create_time";
    query = mydb->query(table, cols, keyword, order, limit);
    refresh(query);
}

//查询和重置
void UserMgmt::on_btn_search_clicked()
{
    keyword = defalut_keyword;
    if(!ui->le_login_name->text().isEmpty()){
        keyword += QString(" AND u.login_name LIKE '%%1%'").arg(ui->le_login_name->text());
    }
    if(!ui->le_username->text().isEmpty()){
        keyword += QString(" AND username LIKE '%%1%'").arg(ui->le_username->text());
    }
    switchToPage(1);
}
void UserMgmt::on_btn_reset_clicked()
{
    keyword = defalut_keyword;
    switchToPage(1);
}




